package sparsearray;

public class SparseArray {
    public static void main(String[] args) {
        //创建一个原始的二维数组 0表示没有棋子 1表示黑子 2表示白子
        int[][] charArr1 = new int[11][11];
        charArr1[1][2] = 1;
        charArr1[2][3] = 2;
        //输出二维数组
        System.out.println("原始二维数组");
        for (int[] ints : charArr1) {
            for (int data : ints) {
                System.out.printf("%d\t", data);
            }
            System.out.println();
        }

        int sum = 0;
        for (int i = 0; i < 11; i++) {
            for (int j = 0; j < 11; j++) {
                if (charArr1[i][j] != 0) {
                    sum++;
                }
            }
        }
        System.out.println(sum);

        //创建稀疏数组
        int[][] sparseArr = new int[sum + 1][3];
        //给稀疏数组赋值
        sparseArr[0][0] = 11;
        sparseArr[0][1] = 11;
        sparseArr[0][2] = sum;
        //遍历二维数组，将非0数据放入稀疏数组
        int count = 0;
        for (int i = 0; i < 11; i++) {
            for (int j = 0; j < 11; j++) {
                if (charArr1[i][j] != 0) {
                    count++;
                    sparseArr[count][0] = i;
                    sparseArr[count][1] = j;
                    sparseArr[count][2] = charArr1[i][j];
                }
            }
        }

        System.out.println("稀疏数组为如下");
        for (int i = 0; i < sparseArr.length; i++) {
            System.out.println(sparseArr[i][0] + " " + sparseArr[i][1] + " " + sparseArr[i][2]);
        }
        System.out.println("将稀疏数组转成原始的二维数组");
        int[][] chessArr2 = new int[sparseArr[0][0]][sparseArr[0][1]];
        for (int i = 1; i < sparseArr.length; i++) {
            chessArr2[sparseArr[i][0]][sparseArr[i][1]] = sparseArr[i][2];
        }
        for (int[] ints : chessArr2) {
            for (int data : ints) {
                System.out.printf("%d\t", data);
            }
            System.out.println();
        }
    }
}
